package JVM;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;

public class PhantomReferenceTry {
    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<String> queue = new ReferenceQueue<>();
        List<MyResource> list = new ArrayList<>();
        list.add(new MyResource(new String("a"),queue));
        list.add(new MyResource("b",queue));
        list.add(new MyResource("c",queue));
        System.gc();
        Thread.sleep(100);
        Object ref = null ;
        while((ref = queue.poll()) != null){
            if(ref instanceof MyResource ){
                ((MyResource)ref).clear();
            }
        }
    }
    public static class MyResource extends PhantomReference<String> {

        public MyResource(String referent, ReferenceQueue<? super String> q) {
            super(referent, q);
        }

        @Override
        public void clear() {
            System.out.println("clean");
        }
    }
}
